import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { jwtConstants } from '../../common/constants';
import { UnauthorizedException } from '@nestjs/common';
import { RedisService } from '../redis/redis.service';

@Injectable()
export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(private readonly redisService: RedisService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  // 验证JWT token
  async validate(payload: any) {
    console.log(payload);
    const token = await this.redisService.get(payload.id.toString());
    if (token) {
      return { id: payload.id, username: payload.username };
    } else {
      throw new UnauthorizedException();
    }
    // return { id: payload.id, username: payload.username };
  }
}